import axios from "axios";
import { notification } from "antd";
const request = axios.create({
  // baseURL: '/ecos',
  headers: {
    // 'Content-Type': 'application/x-www-form-urlencoded',
    // 将token放这一层
    Authorization: window.userinfo.token || "",
  },
  // headers: { 'X-Custom-Header': 'foobar' }
});

request.interceptors.request.use(
  (config: any) => {
    if (config.method == "get") {
      config.params = { ...config.params, _: Date.now() }; //ie下接口缓存问题
    }

    return config;
  },
  (err: any) => Promise.reject(err)
);

const err = (error: any) => {
  if (error.response) {
    const data = error.response.data;
    if (error.response.status >= 500) {
      notification.warning({
        message: "Prompt",
        description: data.message || "Server error",
      });
    }

    if (error.response.status === 400 || error.response.status === 409) {
      notification.warning({
        message: "Prompt",
        // description: 'Bad request',
        description: error.response.data.message || "Bad request",
      });
    }
    if (error.response.status === 404) {
      notification.warning({
        message: "Prompt",
        description: "Resource not found",
      });
    }
    if (error.response.status === 403) {
      notification.warning({
        message: "Prompt",
        description: "No permissions",
      });
    }
    if (error.response.status === 301) {
      // location.href = '/oauth';
    }
    if (error.response.status === 401) {
      notification.warning({
        message: "Prompt",
        description:
          "You have signed in on another device or the login timed out",
      });
      window.location.href = "/logout";
    }
  }
  return Promise.reject(error);
};

request.interceptors.response.use((res: any) => {
  return res;
}, err);

export default request;
